using System;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Collections.Generic;

namespace My.IdlConverter.Core.Output
{
    public class TextStreamWriter<T> : StreamWriterBase<T>
    {
        public TextStreamWriter(string pathName)
            : base(pathName)
        {
        }

        public override void Append(T target)
        {
            InternalWrite(target, true,FileMode.Append);
        }

        public override void Write(T target)
        {
            InternalWrite(target, false, FileMode.Truncate);
        }

        private void InternalWrite(T target, bool isAppend,FileMode filemode)
        {
            Stream Write = null;
            try
            {
                if (File.Exists(Path) == false)
                {
                    Write = File.Create(Path);
                }
                else
                {
                    Write = File.Open(Path, filemode);
                }
                if (isAppend)
                    Write.Seek(0, SeekOrigin.End);
                StreamWriter writer = new StreamWriter(Write);
                writer.WriteLine(target.ToString());
                writer.Flush();
                writer.Close();
            }
            catch (IOException ioe)
            {
                Debug.Assert(false);
                Debug.WriteLine(ioe.Message);
            }
        }
    }
}
